#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , lRealPlayHandle(-1)
    , lUserID(-1)
{
    ui->setupUi(this);

    g_BGRImage = cv::Mat();
    g_nPort = -1;

    ui->pushButton_login->setEnabled(true);
    ui->pushButton_realplay->setEnabled(false);
    qRegisterMetaType<cv::Mat>("cv::Mat");
    connect(this, &MainWindow::newImageReady, this, &MainWindow::onNewImageReady);
    connect(ui->pushButton_login, &QPushButton::clicked, this, &MainWindow::on_pushButton_login_clicked);
    connect(ui->pushButton_realplay, &QPushButton::toggled, this, &MainWindow::on_pushButton_realplay_clicked);
    connect(ui->pushButton_left, &QPushButton::toggled, this, &MainWindow::on_pushButton_left_clicked);
    connect(ui->pushButton_right, &QPushButton::toggled, this, &MainWindow::on_pushButton_right_clicked);
    connect(ui->pushButton_up, &QPushButton::toggled, this, &MainWindow::on_pushButton_up_clicked);
    connect(ui->pushButton_down, &QPushButton::toggled, this, &MainWindow::on_pushButton_down_clicked);
    connect(ui->pushButton_left_up, &QPushButton::toggled, this, &MainWindow::on_pushButton_left_up_clicked);
    connect(ui->pushButton_right_up, &QPushButton::toggled, this, &MainWindow::on_pushButton_right_up_clicked);
    connect(ui->pushButton_left_down, &QPushButton::toggled, this, &MainWindow::on_pushButton_left_down_clicked);
    connect(ui->pushButton_right_down, &QPushButton::toggled, this, &MainWindow::on_pushButton_right_down_clicked);
    connect(ui->pushButton_narrowfocus, &QPushButton::toggled, this, &MainWindow::on_pushButton_narrowfocus_clicked);
    connect(ui->pushButton_expandfocus, &QPushButton::toggled, this, &MainWindow::on_pushButton_expandfocus_clicked);
    connect(ui->pushButton_nearfocus, &QPushButton::toggled, this, &MainWindow::on_pushButton_nearfocus_clicked);
    connect(ui->pushButton_farfocus, &QPushButton::toggled, this, &MainWindow::on_pushButton_farfocus_clicked); 
    connect(ui->pushButton_scrashPic, &QPushButton::clicked, this, &MainWindow::on_pushButton_scrashPic_clicked);
    connect(ui->pushButton_record, &QPushButton::toggled, this, &MainWindow::on_pushButton_record_clicked);
    connect(ui->pushButton_getDVRConfig, &QPushButton::clicked, this, &MainWindow::on_pushButton_getDVRConfig_clicked);
    connect(ui->pushButton_setDVRConfig, &QPushButton::clicked, this, &MainWindow::on_pushButton_setDVRConfig_clicked);
    // 这个相机应该是不支持光圈变化，先留着
    connect(ui->pushButton_smallaperture, &QPushButton::toggled, this, &MainWindow::on_pushButton_smallaperture_clicked);
    connect(ui->pushButton_largeaperture, &QPushButton::toggled, this, &MainWindow::on_pushButton_largeaperture_clicked);
    // 这个相机应该是不支持云台运动速度变化，先留着
    connect(ui->comboBox_ptzspeed, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &MainWindow::on_comboBox_ptzspeed_currentIndexChanged);
    connect(ui->comboBox_day_or_night, &QComboBox::currentTextChanged, this, &MainWindow::on_comboBox_day_or_night_currentTextChanged);
}

MainWindow::~MainWindow()
{
    // 停止预览和释放资源
    if (lRealPlayHandle >= 0)
    {
        NET_DVR_StopRealPlay(lRealPlayHandle);
    }
    NET_DVR_Logout_V30(lUserID);
    NET_DVR_Cleanup();
}

void MainWindow::on_pushButton_login_clicked()
{
    // 初始化海康威视 SDK
    NET_DVR_Init();
    ui->textEdit_msg->append("相机初始化成功");

    // 登录到设备
    NET_DVR_USER_LOGIN_INFO struLoginInfo = {0};
    NET_DVR_DEVICEINFO_V40 struDeviceInfoV40 = {0};
    struLoginInfo.bUseAsynLogin = false;
    struLoginInfo.wPort = ui->lineEdit_Port->text().toInt();
    memcpy(struLoginInfo.sDeviceAddress, ui->lineEdit_IP->text().toStdString().c_str(), NET_DVR_DEV_ADDRESS_MAX_LEN);
    memcpy(struLoginInfo.sUserName, ui->lineEdit_User->text().toStdString().c_str(), NAME_LEN);
    memcpy(struLoginInfo.sPassword, ui->lineEdit_Password->text().toStdString().c_str(), NAME_LEN);
    lUserID = NET_DVR_Login_V40(&struLoginInfo, &struDeviceInfoV40);

    if (lUserID < 0) {
        printf("Login error, %d\n", NET_DVR_GetLastError());
        int errorCode = NET_DVR_GetLastError();
        QString errorMsg = QString("<font color='red'>Login error, %1</font>").arg(errorCode);
        ui->textEdit_msg->append(errorMsg);
        return;
    } else {
        ui->textEdit_msg->append("相机登录成功");
        ui->pushButton_realplay->setEnabled(true);

        // timer->start(200);
        QtConcurrent::run(this,&MainWindow::loop_getDVRConfig);
    }
}

void MainWindow::on_pushButton_realplay_clicked(bool toggled_flag)
{
    if (toggled_flag) {
        ui->pushButton_realplay->setText("关闭相机");

        getPort();

        // 开启实时流
        NET_DVR_PREVIEWINFO struPlayInfo = {0};
        struPlayInfo.lChannel = 1;  // 通道号
        // struPlayInfo.hPlayWnd = (HWND)ui->label_video->winId();
        struPlayInfo.hPlayWnd = 0;
        struPlayInfo.dwStreamType = 0;
        struPlayInfo.dwLinkMode = 0;
        struPlayInfo.bBlocked = 1;
        struPlayInfo.dwDisplayBufNum = 1;
        lRealPlayHandle = NET_DVR_RealPlay_V40(lUserID, &struPlayInfo, g_RealDataCallBack_V30, this);

        if (lRealPlayHandle < 0) {
            int errorCode = NET_DVR_GetLastError();
            printf("Error Code: %d\n", errorCode);
            QString errorMsg = QString("<font color='red'>Login error, %1</font>").arg(errorCode);
            ui->textEdit_msg->append(errorMsg);
            printf("NET_DVR_RealPlay_V40 error\n");
            ui->textEdit_msg->append("<font color='red'>NET_DVR_RealPlay_V40 error</font>");
            NET_DVR_Logout_V30(lUserID);
            NET_DVR_Cleanup();
            return;
        } else {
            ui->textEdit_msg->append("相机显示画面");
            ui->pushButton_login->setEnabled(false);
        }
    } else {
        ui->pushButton_realplay->setText("打开相机");

        // 停止预览和释放资源
        if (lRealPlayHandle >= 0)
        {
            NET_DVR_StopRealPlay(lRealPlayHandle);
        }
        NET_DVR_Logout_V30(lUserID);
        NET_DVR_Cleanup();
        ui->textEdit_msg->append("相机已关闭，请重新登录");
        ui->pushButton_login->setEnabled(true);
        ui->pushButton_realplay->setEnabled(false);
    }

}

void MainWindow::loop_getDVRConfig()
{
    while (true)
    {
        //读取相机信息
        NET_DVR_PTZPOS m_ptzPosCurrent;
        DWORD dwtmp;
        //获取PTZ的信息
        if (!NET_DVR_GetDVRConfig(lUserID, NET_DVR_GET_PTZPOS, 1, &m_ptzPosCurrent, sizeof(NET_DVR_PTZPOS), &dwtmp)) {
            // qDebug() << "NET_DVR_GetDVRConfig Error, SDK_LASTERROR = " << NET_DVR_GetLastError();

            // int errorCode = NET_DVR_GetLastError();
            // QString errorMsg = QString("<font color='red'>NET_DVR_GetDVRConfig Error, SDK_LASTERROR = %1</font>").arg(errorCode);
            // ui->textEdit_msg->append(errorMsg);
        }
        //转换相机信息到十进制
        int m_iPara1 = HexToDecMa(m_ptzPosCurrent.wPanPos);
        int m_iPara2 = HexToDecMa(m_ptzPosCurrent.wTiltPos);
        int m_iPara3 = HexToDecMa(m_ptzPosCurrent.wZoomPos);
        QVector<int> TempPosture(3);//三个参数代表含义如下cout所示
        TempPosture[0] = m_iPara1 / 10;
        TempPosture[1] = m_iPara2 / 10;
        TempPosture[2] = m_iPara3 / 10;

        ui->label_panPos_value->setText(QString::number(TempPosture[0]) + "°");
        ui->label_tiltPos_value->setText(QString::number(TempPosture[1]) + "°");
        ui->label_zoomPos_value->setText(QString::number(TempPosture[2]));

        delay_MSec(100);
    }
}

void MainWindow::on_pushButton_scrashPic_clicked()
{
    if (lRealPlayHandle < 0)
    {
        int errorCode = NET_DVR_GetLastError();
        QString errorMsg = QString("<font color='red'>Have no realplay yet. Please Play Video First!</font>").arg(errorCode);
        ui->textEdit_msg->append(errorMsg);
    } else {
        bool isSucc = false;
        QDir directory("");
        QString filepath = QDir::currentPath();
        QString currDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss");
        filepath.append("/pic/");
        directory.mkpath(filepath);
        filepath.append(currDateTime);
        if (ui->comboBox_image_type->currentText() == "BMP")
        {
            filepath.append(".bmp");
            // 调用函数NET_DVR_CapturePicture时，truPlayInfo.hPlayWnd不能为0。但是有时好像又可以为0
            isSucc = NET_DVR_CapturePicture(lRealPlayHandle, filepath.toLatin1().data());
        } else if (ui->comboBox_image_type->currentText() == "JPEG") {
            filepath.append(".jpg");
            LPNET_DVR_JPEGPARA jpegPara;
            jpegPara->wPicSize = 0xff; // 自动分辨率
            jpegPara->wPicQuality = 2; // 图像质量：0-最好，1-较好，2-一般
            isSucc = NET_DVR_CaptureJPEGPicture(lUserID, 1, jpegPara, filepath.toLatin1().data());
        }
        if (!isSucc)
        {
            int errorCode = NET_DVR_GetLastError();
            QString errorMsg = QString("<font color='red'>NET_DVR_CapturePicture Error, SDK_LASTERROR = %1</font>").arg(errorCode);
            ui->textEdit_msg->append(errorMsg);
        }
        else
        {
            int errorCode = NET_DVR_GetLastError();
            QString errorMsg = QString("NET_DVR_CapturePicture succ!");
            ui->textEdit_msg->append(errorMsg);
        }
    }
}

void MainWindow::on_pushButton_record_clicked(bool toggled_flag)
{
    if (toggled_flag) {
        QDir directory("");
        QString filepath = QDir::currentPath();
        QString currDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss");
        filepath.append("/pic/");
        directory.mkpath(filepath);
        filepath.append(currDateTime);
        filepath.append(".mp4");

        if (!NET_DVR_SaveRealData(lRealPlayHandle, filepath.toLatin1().data()))
        {
            int errorCode = NET_DVR_GetLastError();
            QString errorMsg = QString("<font color='red'>NET_DVR_SaveRealData Error, SDK_LASTERROR = %1</font>").arg(errorCode);
            ui->textEdit_msg->append(errorMsg);
        }
		else
		{
            ui->textEdit_msg->append("Cam start record!");
            ui->pushButton_record->setText("停止录像");

		}
    } else {
        if (!NET_DVR_StopSaveRealData(lRealPlayHandle))
        {
            int errorCode = NET_DVR_GetLastError();
            QString errorMsg = QString("<font color='red'>NET_DVR_StopSaveRealData Error, SDK_LASTERROR = %1</font>").arg(errorCode);
            ui->textEdit_msg->append(errorMsg);
        }
		else
		{
			ui->textEdit_msg->append("Cam stop record!");
            ui->pushButton_record->setText("开始录像");
		}
    }
}

//相机的角度参数是十六进制,需要和十进制来回切换
int MainWindow::HexToDecMa(int wHex)//十六进制转十进制
{
    return (wHex / 4096) * 1000 + ((wHex % 4096) / 256) * 100 + ((wHex % 256) / 16) * 10 + (wHex % 16);
}

int MainWindow::DEC2HEX_doc(int x)//十进制转十六进制
{
    return (x / 1000) * 4096 + ((x % 1000) / 100) * 256 + ((x % 100) / 10) * 16 + x % 10;
}

void MainWindow::on_pushButton_getDVRConfig_clicked()
{
    //读取相机信息
    NET_DVR_PTZPOS m_ptzPosCurrent;
    DWORD dwtmp;
    //获取PTZ的信息
    if (!NET_DVR_GetDVRConfig(lUserID, NET_DVR_GET_PTZPOS, 1, &m_ptzPosCurrent, sizeof(NET_DVR_PTZPOS), &dwtmp)) {
        // qDebug() << "NET_DVR_GetDVRConfig Error, SDK_LASTERROR = " << NET_DVR_GetLastError();

        // int errorCode = NET_DVR_GetLastError();
        // QString errorMsg = QString("<font color='red'>NET_DVR_GetDVRConfig Error, SDK_LASTERROR = %1</font>").arg(errorCode);
        // ui->textEdit_msg->append(errorMsg);
    }
    //转换相机信息到十进制
    int m_iPara1 = HexToDecMa(m_ptzPosCurrent.wPanPos);
    int m_iPara2 = HexToDecMa(m_ptzPosCurrent.wTiltPos);
    int m_iPara3 = HexToDecMa(m_ptzPosCurrent.wZoomPos);
    QVector<int> TempPosture(3);//三个参数代表含义如下cout所示
    TempPosture[0] = m_iPara1 / 10;
    TempPosture[1] = m_iPara2 / 10;
    TempPosture[2] = m_iPara3 / 10;

    ui->label_panPos_value->setText(QString::number(TempPosture[0]) + "°");
    ui->label_tiltPos_value->setText(QString::number(TempPosture[1]) + "°");
    ui->label_zoomPos_value->setText(QString::number(TempPosture[2]));
}

void MainWindow::on_pushButton_setDVRConfig_clicked()
{
    //读取相机信息
    NET_DVR_PTZPOS m_ptzPosCurrent;
    DWORD dwtmp;
    //获取PTZ的信息
    if (!NET_DVR_GetDVRConfig(lUserID, NET_DVR_GET_PTZPOS, 1, &m_ptzPosCurrent, sizeof(NET_DVR_PTZPOS), &dwtmp)) {
        int errorCode = NET_DVR_GetLastError();
        QString errorMsg = QString("<font color='red'>NET_DVR_GetDVRConfig Error, SDK_LASTERROR = %1</font>").arg(errorCode);
        ui->textEdit_msg->append(errorMsg);
    }
    //转换相机信息到十进制
    int m_iPara1 = HexToDecMa(m_ptzPosCurrent.wPanPos);
    int m_iPara2 = HexToDecMa(m_ptzPosCurrent.wTiltPos);
    int m_iPara3 = HexToDecMa(m_ptzPosCurrent.wZoomPos);
    QVector<int> TempPosture(3);//三个参数代表含义如下cout所示
    TempPosture[0] = m_iPara1 / 10;
    TempPosture[1] = m_iPara2 / 10;
    TempPosture[2] = m_iPara3 / 10;

    //设置想要变化的参数值
    QVector<int> Changevalue(3);
    Changevalue[0]=(ui->lineEdit_panPos_setvalue->text().toInt());//degree水平加30度
    Changevalue[1]=(ui->lineEdit_tiltPos_setvalue->text().toInt());//degree俯仰减10度
    Changevalue[2]=(ui->lineEdit_zoomPos_setvalue->text().toInt());//焦距加1
    //定义目标参数
    QVector<int> TargetPosture(3);
    //将变化值更新
    TargetPosture[0]=TempPosture[0]+Changevalue[0];
    TargetPosture[1]=TempPosture[1]+Changevalue[1];
    TargetPosture[2]=TempPosture[2]+Changevalue[2];
    if (TargetPosture[0] >= 360) {
        TargetPosture[0] -= 360;
    } else if (TargetPosture[0] < 0) {
        TargetPosture[0] += 360;
    }

    //将变化后的参数转化为相机自带的十六进制
    m_ptzPosCurrent.wPanPos = DEC2HEX_doc(TargetPosture[0]*10);
    m_ptzPosCurrent.wTiltPos = DEC2HEX_doc(TargetPosture[1]*10);
    m_ptzPosCurrent.wZoomPos = DEC2HEX_doc(TargetPosture[2]*10);

    //将参数传入函数,相机开始调整位置
    if (!NET_DVR_SetDVRConfig(lUserID, NET_DVR_SET_PTZPOS, 1, &m_ptzPosCurrent, sizeof(NET_DVR_PTZPOS))) {
        int errorCode = NET_DVR_GetLastError();
        QString errorMsg = QString("<font color='red'>NET_DVR_SetDVRConfig Error, SDK_LASTERROR = %1</font>").arg(errorCode);
        ui->textEdit_msg->append(errorMsg);
    }
}

// 在主窗口中接收信号并保存图像
void MainWindow::onNewImageReady(const cv::Mat& mat)
{
    if (!mat.empty()) {
        QImage qImage;
    
        if (mat.channels() == 3) {
            // For BGR (which is default for OpenCV)
            qImage = QImage(mat.data, mat.cols, mat.rows, mat.step, QImage::Format_BGR888);
        } else if (mat.channels() == 1) {
            // For Grayscale images
            qImage = QImage(mat.data, mat.cols, mat.rows, mat.step, QImage::Format_Grayscale8);
        }
        // Convert QImage to QPixmap
        QPixmap pixmap = QPixmap::fromImage(qImage);
        
        // Display the image on QLabel
        ui->label_video->setPixmap(pixmap.scaled(ui->label_video->size(), Qt::KeepAspectRatio));
    }
}

//获取播放库通道号
void MainWindow::getPort() 
{
	if (PlayM4_GetPort(&g_nPort))
	{
		if (PlayM4_SetStreamOpenMode(g_nPort, STREAME_REALTIME))      //设置流模式
		{
			if (PlayM4_OpenStream(g_nPort, NULL, 0, 1440 * 2560))         //打开流
			{
				if (PlayM4_SetDecCallBackExMend(g_nPort, DecCBFun, NULL, 0, this))
				{
					if (PlayM4_Play(g_nPort, 0))
                    {
						std::cout << "success to set play mode" << std::endl;
                    }
					else
						std::cout << "fail to set play mode" << std::endl;
				}
				else
					std::cout << "fail to set dec callback " << std::endl;
			}
			else
				std::cout << "fail to open stream" << std::endl;
		}
		else
			std::cout << "fail to set stream open mode" << std::endl;
	}
	else
		std::cout << "fail to get port" << std::endl;
}

void CALLBACK MainWindow::DecCBFun(int nPort, char* pBuf, int nSize, FRAME_INFO* pFrameInfo, void* nUser, int nReserved2)
{
    MainWindow* instance = static_cast<MainWindow*>(nUser);
	if (pFrameInfo->nType == T_YV12)
	{
		// std::cout << "the frame infomation is T_YV12" << std::endl;
		if (instance->g_BGRImage.empty())
		{
            std::cout << "g_BGRImage: " << instance->g_BGRImage.empty() << std::endl;
			instance->g_BGRImage.create(pFrameInfo->nHeight, pFrameInfo->nWidth, CV_8UC3);
		}
		cv::Mat YUVImage(pFrameInfo->nHeight + pFrameInfo->nHeight / 2, pFrameInfo->nWidth, CV_8UC1, (unsigned char*)pBuf);

		cv::cvtColor(YUVImage, instance->g_BGRImage, cv::COLOR_YUV2BGR_YV12);

		if (!instance->g_BGRImage.empty()) {
            emit instance->newImageReady(instance->g_BGRImage);
		}
	}
}

//实时视频码流数据获取 回调函数
void CALLBACK MainWindow::g_RealDataCallBack_V30(LONG lPlayHandle, DWORD dwDataType, BYTE* pBuffer, DWORD dwBufSize, void* pUser)
{
    MainWindow* instance = static_cast<MainWindow*>(pUser);

	if (dwDataType == NET_DVR_STREAMDATA)//码流数据
	{
		if (dwBufSize > 0 && instance->g_nPort != -1)
		{
			if (!PlayM4_InputData(instance->g_nPort, pBuffer, dwBufSize))
			{
				// std::cout << "fail input data" << std::endl;
			}
		}
	}
}

void MainWindow::delay_MSec(unsigned int msec)
{
    QEventLoop loop; // 定义一个新的事件循环
    QTimer::singleShot(msec, &loop, &QEventLoop::quit); // 创建单次定时器，槽函数为事件循环的退出函数
    loop.exec(); // 事件循环开始执行，程序会卡在这里，直到定时时间到，本循环被退出
}

void MainWindow::on_pushButton_left_clicked(bool toggled_flag)
{
    if (toggled_flag) {
        ptzControlRealPlay(PAN_LEFT, 0);
    } else {
        ptzControlRealPlay(PAN_LEFT, 1);
    }
}

void MainWindow::on_pushButton_right_clicked(bool toggled_flag)
{
    if (toggled_flag) {
        ptzControlRealPlay(PAN_RIGHT, 0);
    } else {
        ptzControlRealPlay(PAN_RIGHT, 1);
    }
}

void MainWindow::on_pushButton_up_clicked(bool toggled_flag)
{
    if (toggled_flag) {
        ptzControlRealPlay(TILT_UP, 0);
    } else {
        ptzControlRealPlay(TILT_UP, 1);
    }
}

void MainWindow::on_pushButton_down_clicked(bool toggled_flag)
{
    if (toggled_flag) {
        ptzControlRealPlay(TILT_DOWN, 0);
    } else {
        ptzControlRealPlay(TILT_DOWN, 1);
    }
}

void MainWindow::on_pushButton_left_up_clicked(bool toggled_flag)
{
    if (toggled_flag) {
        ptzControlRealPlay(UP_LEFT, 0);
    } else {
        ptzControlRealPlay(UP_LEFT, 1);
    }
}

void MainWindow::on_pushButton_right_up_clicked(bool toggled_flag)
{
    if (toggled_flag) {
        ptzControlRealPlay(UP_RIGHT, 0);
    } else {
        ptzControlRealPlay(UP_RIGHT, 1);
    }
}

void MainWindow::on_pushButton_left_down_clicked(bool toggled_flag)
{
    if (toggled_flag) {
        ptzControlRealPlay(DOWN_LEFT, 0);
    } else {
        ptzControlRealPlay(DOWN_LEFT, 1);
    }
}

void MainWindow::on_pushButton_right_down_clicked(bool toggled_flag)
{
    if (toggled_flag) {
        ptzControlRealPlay(DOWN_RIGHT, 0);
    } else {
        ptzControlRealPlay(DOWN_RIGHT, 1);
    }
}

void MainWindow::on_pushButton_narrowfocus_clicked(bool toggled_flag)
{
    if (toggled_flag) {
        ptzControlRealPlay(ZOOM_OUT, 0);
    } else {
        ptzControlRealPlay(ZOOM_OUT, 1);
    }
}

void MainWindow::on_pushButton_expandfocus_clicked(bool toggled_flag)
{
    if (toggled_flag) {
        ptzControlRealPlay(ZOOM_IN, 0);
    } else {
        ptzControlRealPlay(ZOOM_IN, 1);
    }
}

void MainWindow::on_pushButton_nearfocus_clicked(bool toggled_flag)
{
    if (toggled_flag) {
        ptzControlRealPlay(FOCUS_NEAR, 0);
    } else {
        ptzControlRealPlay(FOCUS_NEAR, 1);
    }
}

void MainWindow::on_pushButton_farfocus_clicked(bool toggled_flag)
{
    if (toggled_flag) {
        ptzControlRealPlay(FOCUS_FAR, 0);
    } else {
        ptzControlRealPlay(FOCUS_FAR, 1);
    }
}

void MainWindow::on_pushButton_smallaperture_clicked(bool toggled_flag)
{
    if (toggled_flag) {
        ptzControlRealPlay(IRIS_CLOSE, 0);
    } else {
        ptzControlRealPlay(IRIS_CLOSE, 1);
    }
}

void MainWindow::on_pushButton_largeaperture_clicked(bool toggled_flag)
{
    if (toggled_flag) {
        ptzControlRealPlay(IRIS_OPEN, 0);
    } else {
        ptzControlRealPlay(IRIS_OPEN, 1);
    }
}

void MainWindow::ptzControlRealPlay(int command,int flag)
{
    if (!NET_DVR_PTZControl(lRealPlayHandle, command, flag))
    {
        int errorCode = NET_DVR_GetLastError();
        QString errorMsg = QString("<font color='red'>NET_DVR_PTZControl, SDK_LASTERROR = %1</font>").arg(errorCode);
        ui->textEdit_msg->append(errorMsg);
    }
}

void MainWindow::on_comboBox_ptzspeed_currentIndexChanged(int index)
{
    int rpptzspeed = 4;

    if (index == 0)
    {
        rpptzspeed = 4;
    }
	else
	{
		rpptzspeed = index;
	}
    
    if (!NET_DVR_PTZControlWithSpeed(lRealPlayHandle, SET_SEQ_SPEED, 0, rpptzspeed))
    {
        int errorCode = NET_DVR_GetLastError();
        QString errorMsg = QString("<font color='red'>NET_DVR_PTZControl, SDK_LASTERROR = %1</font>").arg(errorCode);
        ui->textEdit_msg->append(errorMsg);
    }
    else
    {
    	NET_DVR_PTZControlWithSpeed(lRealPlayHandle, SET_SEQ_SPEED, 1, rpptzspeed);
    }
}

void MainWindow::on_comboBox_day_or_night_currentTextChanged(const QString &text)
{
    // ############################ 这个方式不行 总报错17 先放这儿 等海康回复 ############################
    // // 设置日夜模式
    // NET_DVR_DAYNIGHT videoDayNight = {0}; // 图像参数结构体

    // DWORD dwtmp;
    // //获取PTZ的信息
    // if (!NET_DVR_GetDVRConfig(lUserID, NET_DVR_GET_DEFAULT_VIDEO_EFFECT, 1, &videoDayNight, sizeof(NET_DVR_DAYNIGHT), &dwtmp)) {
    //     int errorCode = NET_DVR_GetLastError();
    //     QString errorMsg = QString("<font color='red'>NET_DVR_GetDVRConfig Error, SDK_LASTERROR = %1 %2</font>").arg(errorCode).arg(videoDayNight.byDayNightFilterType);
    //     ui->textEdit_msg->append(errorMsg);
    // }

    // if (text == "白天") {
    //     qDebug() << "白天";
    //     videoDayNight.byDayNightFilterType = 0;
    //     if (!NET_DVR_SetDVRConfig(lUserID, NET_DVR_SET_VIDEO_EFFECT, 1, &videoDayNight, sizeof(NET_DVR_DAYNIGHT))) {
    //         std::cerr << "Failed to set day/night mode! Error code: " << NET_DVR_GetLastError() << std::endl;
    //     } else {
    //         std::cout << "Day/Night mode set successfully!" << std::endl;
    //     }
    // } else if (text == "夜晚") {
    //     qDebug() << "夜晚";
    //     videoDayNight.byDayNightFilterType = 1;
    //     if (!NET_DVR_SetDVRConfig(lUserID, NET_DVR_SET_VIDEO_EFFECT, 1, &videoDayNight, sizeof(NET_DVR_DAYNIGHT))) {
    //         std::cerr << "Failed to set day/night mode! Error code: " << NET_DVR_GetLastError() << std::endl;
    //     } else {
    //         std::cout << "Day/Night mode set successfully!" << std::endl;
    //     }
    // } else if (text == "自动") {
    //     qDebug() << "自动";
    //     videoDayNight.byDayNightFilterType = 2;
    //     if (!NET_DVR_SetDVRConfig(lUserID, NET_DVR_SET_VIDEO_EFFECT, 1, &videoDayNight, sizeof(NET_DVR_DAYNIGHT))) {
    //         std::cerr << "Failed to set day/night mode! Error code: " << NET_DVR_GetLastError() << std::endl;
    //     } else {
    //         std::cout << "Day/Night mode set successfully!" << std::endl;
    //     }
    // }
}